import 'package:flutter/material.dart';

class WillPopScopeTestRoute extends StatefulWidget {
  @override
  WillPopScopeTestRouteState createState() {
    return WillPopScopeTestRouteState();
  }
}

class WillPopScopeTestRouteState extends State<WillPopScopeTestRoute> {
  DateTime? _lastPressedAt; //上次点击时间

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if (_lastPressedAt == null ||
            DateTime.now().difference(_lastPressedAt!) > Duration(seconds: 1)) {
          //两次点击间隔超过1秒则重新计时
          _lastPressedAt = DateTime.now();
          return false;
        }
        return true;
      },
      child: Center(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('1. 功能：点击两次退出'),
            Text("2. 但是只有点击“导航返回按钮及Android物理返回按钮”才会触发onWillPop，所以web端不会触发"),
            TextButton(
              onPressed: () {
                Navigator.pop(context);
              },
              child: Text("按钮模拟路由, 不会触发onWillPop的"),
            )
          ],
        ),
      ),
    );
  }
}

void main(List<String> args) {
  runApp(MaterialApp(
    home: Scaffold(body: WillPopScopeTestRoute()),
  ));
}
